<?php
/**
 * 支付
 */

namespace app\api\controller;

use app\common\Base;
use think\facade\Validate;

class WxPay extends Base {
    /**
     * 生成订单
     * @return \think\response\Json
     */
    public function makeOrder(): \think\response\Json {
        $postData=$this->request->post();
        $validate = Validate::rule([
            "id|商品标识" => "require|integer",
            "num|购买数量" => "require"
        ]);
        if (!$validate->check($postData)) {
            return error($validate->getError());
        }
        try {
            //判断商品是否存在，是否下架
            //1不存在 error('商品已下架')

            //判断商品库存
            //1库存小于购买数量 error('库存不足')
            //2.库存大于购买数量，生成订单，库存-1
            $WxPay = new \app\server\WxPay();
            $data=[
                'body' => '腾讯充值中心-QQ会员充值',
                'out_trade_no' => date('YmdHis',$this->Time).rand_code(),
                'total_fee' => floatval($postData['price'] * 100),
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->request->master['openid'],
            ];
            $result=$WxPay->makeOrder($data);
            if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS'){
                return error('订单生成失败');
            }else{
                //订单信息入库
                if ($res) {
                    $config = $WxPay->bridgeConfig($result['prepay_id']);
                    return success('ok', ['config' => $config]);
                } else {
                    return error('创建订单失败');
                }
            }
        }catch (\Exception $exception){
            return error($exception->getMessage());
        }

    }

    /**
     * 支付成功后查询订单状态
     * @return \think\response\Json
     */
    public function checkOrder(){
        $postData=$this->request->post();
        $validate = Validate::rule([
            "order_no|商品标识" => "require"
        ]);
        if (!$validate->check($postData)) {
            return error($validate->getError());
        }
        $openid=$this->request->master['openid'];
        //查询用户此订单状态
        $order_info='';
        if($order_info['status']==1){
            return success('支付成功');
        }
    }

    /**
     * 支付回调
     */
    public function notify(){
        $WxPay = new \app\server\WxPay();
        $WxPay->notify();
    }
}
